using System;
using System.Collections;
using System.Diagnostics;
using log4net;
using SQLServices.Log;

namespace SQLLog4net.Log
{

	/// <summary>
	/// Summary description for Logger.
	/// </summary>
	public class Logger : 
		IAppLogger
	{

		#region Private Instances

		private System.Collections.ArrayList _runList;
		private IPathItem _defaultPath;
		private ILog _log4net;
		private bool _isLog4NetAvailable = false;

		#endregion
		#region Constructor Methods

		public Logger()
		{
			_runList = new ArrayList();
			_log4net = LogManager.GetLogger(typeof(Logger));
			if ( _log4net != null ) _isLog4NetAvailable = true;
		}

		#endregion
		#region Private Methods

		private ItemLog AddScript(EventType type, string name, string error)
		{
			ItemLog item = new ItemLog(type, name, error, _defaultPath);
			_runList.Add(item);	
			return item;
		}

		#endregion
		#region Public Methods

		public IItemLog AddError(string name, string error)
		{
			LogMessage(String.Format("AddError: name({0}) - error: {1}", 
				name, error));
			return AddScript(EventType.ERROR, name, error);
		}

		public IItemLog AddOk(string name)
		{
			LogMessage(String.Format("AddOk: name({0})", name));
			return AddScript(EventType.OK, name, "");
		}

		public int TotalScripts()
		{
			return _runList.Count;
		}

		public int TotalErrors()
		{
			return Events(true).Count;
		}

		public ArrayList Events(bool onlyErrors)
		{
			ArrayList list = new ArrayList(_runList.Count);
			if (onlyErrors)
			{
				for (int i = 0; i < _runList.Count; i++)
				{
					if (((ItemLog) _runList[i]).Type == EventType.ERROR)
						list.Add(_runList[i]);
				}
			}
			else
			{
				list = _runList;
			}

			return list;
		}

		public void Reset()
		{
			LogMessage("Logger.Reset method was executed");
			_runList = new System.Collections.ArrayList();
		}

		/// <summary>
		/// If not level is specified then we just use the Debug level
		/// in this implementation
		/// </summary>
		/// <param name="message"></param>
		public void LogMessage(string message)
		{
			LogMessage(message, MsgLevel.Debug);
		}

		public void LogMessage(string message, MsgLevel level)
		{
			if ( _isLog4NetAvailable )
			{		
				if ( (level & MsgLevel.DebugBit) == MsgLevel.DebugBit ) {
					_log4net.Debug(message);
					return;
				}
				if ( (level & MsgLevel.InfoBit) == MsgLevel.InfoBit ) {
					_log4net.Info(message);
					return;
				}
				if ( (level & MsgLevel.WarnBit) == MsgLevel.WarnBit ) {
					_log4net.Warn(message);					
					return;
				}
				if ( (level & MsgLevel.ErrorBit) == MsgLevel.ErrorBit ) {
					_log4net.Error(message);
					return;
				}				
			}
		}

		#endregion
		#region Properties

		public IPathItem DefaultPath
		{
			get { return _defaultPath; }
			set { _defaultPath = value; }
		}
		
		#endregion
	}

}
